package net.cyue.web.easyquery.test.spring;

import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Map;

@Component
public class EndpointPrinter {

    /**
     * 应用启动完成后执行，打印所有请求映射路径
     */
    @EventListener(ContextRefreshedEvent.class)
    public void onEvent(ContextRefreshedEvent event) {
        RequestMappingHandlerMapping handlerMapping = event.getApplicationContext()
                .getBean(RequestMappingHandlerMapping.class);
        this.printAllEndpoints(handlerMapping);
    }

    public void printAllEndpoints(RequestMappingHandlerMapping requestMappingHandlerMapping) {
        System.out.println("\n==============================================");
        System.out.println("           所有请求映射路径列表                ");
        System.out.println("==============================================");

        // 获取所有请求映射信息
        Map<RequestMappingInfo, HandlerMethod> handlerMethods =
                requestMappingHandlerMapping.getHandlerMethods();

        // 遍历并打印
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
            RequestMappingInfo info = entry.getKey();
            HandlerMethod method = entry.getValue();

            // 获取URL路径
            if (info.getPatternsCondition() != null) {
                info.getPatternsCondition().getPatterns().forEach(pattern -> {
                    // 获取HTTP方法
                    String httpMethods = info.getMethodsCondition().getMethods().toString();
                    // 获取控制器和方法名
                    String handler = method.getBeanType().getSimpleName() + "." + method.getMethod().getName() + "()";

                    // 格式化输出
                    System.out.printf(
                        "%-10s %-30s %s%n",
                        httpMethods,
                        pattern,
                        handler
                    );
                });
            } else {
                System.err.println("No patterns condition found for " + info);
            }
        }

        System.out.println("==============================================\n");
    }
}
